﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Models;
using Microhard.Core;
using Microhard.WeixinMP.Validators;
using FluentValidation;
using System.Configuration;


namespace Microhard.WeixinMP.Impls
{
    public class SubscribeMe : BaseResponseImpl
    {
        protected override Models.WeixinBaseData<object> CreateFeatureResponse(Models.RequestServiceModel request, Models.WeixinBaseData<object> response)
        {
            IWXMPUser user = IoC.Resolve<IWXMPUser>();
            IWXMPAccount mpa = IoC.Resolve<IWXMPAccount>();

            if (request.Event.Content.Event == WeixinMsgType.Subscribe)
            {
                WeixinTxt welcome = new WeixinTxt();
                var mp = request.WXMPAccountUser;
                welcome.Content = "您好，很高兴为您服务,我们提供的服务如下:" + mp.Welcome;
                response.MsgType = WeixinMsgType.Text; ;
                response.Content = welcome;
                response.FuncFlag = WeixinMsgType.FuncFlag_False;

                //添加到数据库
                var account = mpa.GetModelByModel(new WXMPAccountModel { UserName = request.WXMPAccountUser.UserName });
                //添加前做数据验证
                Guid bei = mp.CompanyID;
                //TODO如果二维码带参数，则取参数为BelongEntityID
                var toAdd = new WXMPUserModel
                {
                    OpenID = response.ToUserName,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    WXUserID = Guid.NewGuid(),
                    WXMPID = account.WXMPID,
                    BelongEntityID = bei
                };
                IValidator<WXMPUserModel> wmModelV = new WXMPUserModelValidator();
                var vRtn = wmModelV.Validate(toAdd, ruleSet: "Insert");
                if (vRtn.IsValid)
                {
                    user.Add(toAdd);
                }
                else
                {
                    Log.Error("SubscribeMe", "添加用户失败，用户数据不合法");
                }
                return response;
            }
            else
            {
                Log.Info("Unsubscribe", response.ToUserName + " 时间 " + DateTime.Now);
                //删除关注用户
                user.Delete(new WXMPUserModel { OpenID = response.ToUserName });
            }
            return response;
        }

        public override Interfaces.WeixinCommand Command
        {
            get
            {
                WeixinCommand cmm = new WeixinCommand();
                cmm.Command = "event";
                cmm.Description = "关注事件";
                return cmm;
            }
        }
    }
}
